<?php

namespace app\admin\controller\performance;

use app\common\controller\Backend;
use app\admin\model\AdminLog;
/**
 * 评分管理
 *
 * @icon fa fa-circle-o
 */
class Performance extends Backend
{
    
    /**
     * Performance模型对象
     */
    protected $model = null;
    /**
     * table搜索字段,避免join条件冲突 也可以在js column field里面添加
     */
    protected $searchFields = 'performance.datekey';
    protected $noNeedLogin = []; //无需登录的方法,同时也就不需要鉴权了
    protected $noNeedRight = ['getList']; //无需鉴权的方法,但需要登录
    
    public function _initialize()
    {
        parent::_initialize();
        $this->childrenAdminIds = $this->auth->getChildAdminIds(true);//不包含自己同级别部门的
        $this->model = model('Performance');
        $this->evalmodel = model('Evaluation');

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */ 

     /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $re_admin_id = $this->request->get("admin_id");
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
           
            if($this->request->get("admin_id")){
                $where2['performance.admin_id'] = $this->request->get("admin_id");
            }else
            {
                $where2['performance.admin_id'] = array("in",$this->childrenAdminIds);
            }
            
            $total = $this->model
                    ->join("admin","admin.id = performance.admin_id")
                    ->where($where)
                    ->where($where2)
                    ->order($sort, $order)
                    ->count();
            $order = "desc";
            $sort = "month";
            $list = $this->model
                    ->join("admin","admin.id = performance.admin_id")
                    ->where($where)
                    ->where($where2)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->field("admin.username,admin.performance,admin.nickname,performance.*")
                    ->select();

            
            //平均分计算
            $month = date("m");
            $year = date("Y");
            foreach ($list as $key => &$value)
            {   $map['month'] = $value['month'];
                $map['year'] = $value['year'];
                $map['admin_id'] = $value['admin_id'];
                $monthscore = $this->evalmodel
                            ->where($map)
                            ->avg("ave_score");
                $monthself_score = $this->evalmodel
                            ->where($map)
                            ->avg("self_score");

                $monthsuperior_score = $this->evalmodel
                            ->where($map)
                            ->avg("superior_score");
                $data['id'] = $value['id'];
                $value['self_score'] = round($monthself_score,2);
                $value['superior_score']  = round($monthsuperior_score,2);
                $value['ave_score']  = round($monthscore,2);
                $data['self_score'] = $monthself_score;
                $data['superior_score']  = $monthsuperior_score;
                $data['ave_score']  = $monthscore;
                $this->model->update($data);

                $value['performance'] = round(($monthscore/5)*$value['performance'],2);//工资
                 
            }

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        $is_super = $this->auth->isSuperAdmin();
        $this->view->assign("admin_id",$re_admin_id);
        $this->view->assign("is_super",$is_super);
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);

        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    if($params['superior_content']){
                        
                        $admin_id = $this->auth->id ? $this->auth->id :0;
                        AdminLog::recordScore($admin_id,$row['admin_id'],$params['superior_content']);
                    }
                    
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 更新个人信息
     */
    public function update()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
           
          
            if ($params)
            {   
                

                $this->model->update($params);
               // $this->success("11",);
                $this->success('编辑成功','performance/admin');
            }
            $this->error();
        }
        return;
    }
    public function getList(){
        $name = $this->request->get("name");
        if(!$name){
            return;
        }
        $result = model($name)->select();
        foreach ($result as $key => $value) {
            $re[$value['id']] = $value['name'];
        }
        return json($re);
    }

}
